#include "monthlyquery.h"
#include "mainwindow.h"
#include "database.h"
#include <QMessageBox>
#include <QStandardPaths>
#include <QDir>
#include <QTimer>
#include <QHeaderView>
#include <QSizePolicy>
#include <QTextStream>
#include <QFile>
#include <QApplication>
#include <QStatusBar>

MonthlyQuery::MonthlyQuery(MainWindow *parent)
    : QWidget(parent), mainWindow(parent), currentSortType(SortByExcellent)
{
    // 获取数据库实例
    database = mainWindow->getDatabase();

    setupUi();
}

MonthlyQuery::~MonthlyQuery()
{
}

void MonthlyQuery::setupUi()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(5);
    mainLayout->setContentsMargins(5, 5, 5, 5);

    // 顶部控制区域
    QHBoxLayout *controlLayout = new QHBoxLayout();

    // 日期范围选择
    QLabel *startDateLabel = new QLabel("开始日期:", this);
    startDateEdit = new QDateEdit(QDate::currentDate().addDays(-30), this);
    startDateEdit->setCalendarPopup(true);
    startDateEdit->setDisplayFormat("yyyy-MM-dd");

    QLabel *endDateLabel = new QLabel("结束日期:", this);
    endDateEdit = new QDateEdit(QDate::currentDate(), this);
    endDateEdit->setCalendarPopup(true);
    endDateEdit->setDisplayFormat("yyyy-MM-dd");

    // 查询按钮
    queryButton = new QPushButton("查询", this);
    queryButton->setStyleSheet("background-color: #007bff; color: white; padding: 5px 15px;");

    controlLayout->addWidget(startDateLabel);
    controlLayout->addWidget(startDateEdit);
    controlLayout->addSpacing(10);
    controlLayout->addWidget(endDateLabel);
    controlLayout->addWidget(endDateEdit);
    controlLayout->addSpacing(20);
    controlLayout->addWidget(queryButton);
    controlLayout->addStretch();

    mainLayout->addLayout(controlLayout);

    // 排序选项
    QHBoxLayout *sortLayout = new QHBoxLayout();

    QLabel *sortLabel = new QLabel("排序方式:", this);
    sortExcellentRadio = new QRadioButton("按优秀次数排序", this);
    sortPoorRadio = new QRadioButton("按问题次数排序", this);

    // 默认选择按优秀次数排序
    sortExcellentRadio->setChecked(true);

    // 按钮组
    QButtonGroup *sortGroup = new QButtonGroup(this);
    sortGroup->addButton(sortExcellentRadio);
    sortGroup->addButton(sortPoorRadio);

    // 导出按钮
    exportExcelButton = new QPushButton("导出Excel", this);
    exportExcelButton->setStyleSheet("background-color: #28a745; color: white; padding: 5px 15px;");

    sortLayout->addWidget(sortLabel);
    sortLayout->addWidget(sortExcellentRadio);
    sortLayout->addWidget(sortPoorRadio);
    sortLayout->addStretch();
    sortLayout->addWidget(exportExcelButton);

    mainLayout->addLayout(sortLayout);

    // 创建一个包含自定义标题和表格的容器widget，使它们成为一个整体
    QWidget *contentWidget = new QWidget(this);
    QVBoxLayout *contentLayout = new QVBoxLayout(contentWidget);
    contentLayout->setSpacing(0);
    contentLayout->setContentsMargins(0, 0, 0, 0);

    // 创建一个自定义标题区域
    QWidget *headerWidget = new QWidget(contentWidget);
    QGridLayout *headerLayout = new QGridLayout(headerWidget);
    headerLayout->setSpacing(0);
    headerLayout->setContentsMargins(1, 1, 1, 1);

    // 创建标题标签
    QStringList mainTitles = {"单元", "房间号", "优的次数", "良的次数", "差"};
    QStringList subTitles = {"消防问题", "抽烟问题", "卫生问题", "安全问题", "差累计"};

    int colIndex = 0;

    // 添加前四个主标题
    for (int i = 0; i < 4; i++)
    {
        QLabel *label = new QLabel(mainTitles[i], headerWidget);
        label->setAlignment(Qt::AlignCenter);
        label->setStyleSheet("background-color: #e0e0e0; border: 1px solid #a0a0a0; font-weight: bold;");
        label->setMinimumHeight(30);
        headerLayout->addWidget(label, 0, colIndex, 2, 1); // 跨2行
        colIndex++;
    }

    // 添加"差"主标题
    QLabel *diffLabel = new QLabel(mainTitles[4], headerWidget);
    diffLabel->setAlignment(Qt::AlignCenter);
    diffLabel->setStyleSheet("background-color: #e0e0e0; border: 1px solid #a0a0a0; font-weight: bold;");
    diffLabel->setMinimumHeight(30);
    headerLayout->addWidget(diffLabel, 0, colIndex, 1, 5); // 跨5列

    // 添加"差"的子标题
    for (int i = 0; i < 5; i++)
    {
        QLabel *label = new QLabel(subTitles[i], headerWidget);
        label->setAlignment(Qt::AlignCenter);
        label->setStyleSheet("background-color: #e8e8e8; border: 1px solid #a0a0a0;");
        label->setMinimumHeight(25);
        headerLayout->addWidget(label, 1, colIndex + i, 1, 1);
    }

    // 设置网格布局的列伸缩因子，使列宽自适应窗口大小变化
    for (int i = 0; i < 9; i++)
    {
        headerLayout->setColumnStretch(i, 1);
    }

    headerWidget->setLayout(headerLayout);
    contentLayout->addWidget(headerWidget);

    // 结果表格 - 无标题，使用上面自定义的标题
    resultTable = new QTableWidget(contentWidget);
    resultTable->setColumnCount(9);
    resultTable->horizontalHeader()->setVisible(false); // 隐藏原始表头
    resultTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    resultTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    resultTable->verticalHeader()->setVisible(false);

    // 设置表格水平标题伸缩模式
    resultTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 设置表格垂直滚动条总是显示
    resultTable->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    // 设置表格的大小策略，使它随容器调整
    resultTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    contentLayout->addWidget(resultTable, 1); // 添加表格并设置伸缩因子为1，表示占用所有可用空间

    // 将内容容器添加到主布局
    mainLayout->addWidget(contentWidget, 1); // 设置伸缩因子为1，使其随窗口大小变化

    // 连接信号和槽
    connect(queryButton, &QPushButton::clicked, this, &MonthlyQuery::onQueryClicked);
    connect(sortExcellentRadio, &QRadioButton::clicked, this, &MonthlyQuery::onSortExcellentClicked);
    connect(sortPoorRadio, &QRadioButton::clicked, this, &MonthlyQuery::onSortPoorClicked);
    connect(exportExcelButton, &QPushButton::clicked, this, &MonthlyQuery::onExportExcelClicked);

    // 注意：不再使用错误的connect语句，改为重写resizeEvent
}

// 重写resizeEvent处理窗口大小变化
void MonthlyQuery::resizeEvent(QResizeEvent *event)
{
    // 调用父类方法
    QWidget::resizeEvent(event);

    // 延迟调用adjustTableColumns，确保布局已经更新
    QTimer::singleShot(0, this, &MonthlyQuery::adjustTableColumns);
}

// 调整表格列宽与标题对齐
void MonthlyQuery::adjustTableColumns()
{
    // 确保表格和标题的列宽一致
    if (resultTable->columnCount() > 0)
    {
        for (int col = 0; col < resultTable->columnCount(); col++)
        {
            // 设置表格列宽为均分可用宽度
            int columnWidth = resultTable->width() / resultTable->columnCount();
            resultTable->setColumnWidth(col, columnWidth);
        }
    }
}

void MonthlyQuery::refreshData()
{
    // 在这个页面中不需要自动加载数据，用户需要手动点击查询按钮
}

void MonthlyQuery::loadData()
{
    // 清空表格
    resultTable->setRowCount(0);
    currentStats.clear();

    // 获取选择的日期范围
    QString startDate = startDateEdit->date().toString("yyyy-MM-dd");
    QString endDate = endDateEdit->date().toString("yyyy-MM-dd");

    // 检查日期范围是否有效
    if (startDateEdit->date() > endDateEdit->date())
    {
        QMessageBox::warning(this, "日期错误", "开始日期不能晚于结束日期");
        return;
    }

    // 查询统计数据
    currentStats = database->getMonthlyStats(startDate, endDate);

    if (currentStats.isEmpty())
    {
        QMessageBox::information(this, "提示", "所选日期范围内没有评分记录");
        return;
    }

    // 对数据进行排序
    sortData();

    // 填充表格
    resultTable->setRowCount(currentStats.size());

    for (int i = 0; i < currentStats.size(); ++i)
    {
        const Database::MonthlyStats &stats = currentStats[i];

        // 重新计算差的累计为问题总数
        int totalIssues = stats.fireIssueCount + stats.smokingIssueCount +
                          stats.sanitaryIssueCount + stats.safetyIssueCount;

        // 更新poorCount为问题总数
        Database::MonthlyStats &modifiableStats = currentStats[i];
        modifiableStats.poorCount = totalIssues;

        // 列的顺序为：单元(0),房间号(1),优的次数(2),良的次数(3),
        // 消防问题(4),抽烟问题(5),卫生问题(6),安全问题(7),差累计(8)
        resultTable->setItem(i, 0, new QTableWidgetItem(stats.unit));
        resultTable->setItem(i, 1, new QTableWidgetItem(stats.room));
        resultTable->setItem(i, 2, new QTableWidgetItem(QString::number(stats.excellentCount)));
        resultTable->setItem(i, 3, new QTableWidgetItem(QString::number(stats.goodCount)));
        resultTable->setItem(i, 4, new QTableWidgetItem(QString::number(stats.fireIssueCount)));
        resultTable->setItem(i, 5, new QTableWidgetItem(QString::number(stats.smokingIssueCount)));
        resultTable->setItem(i, 6, new QTableWidgetItem(QString::number(stats.sanitaryIssueCount)));
        resultTable->setItem(i, 7, new QTableWidgetItem(QString::number(stats.safetyIssueCount)));
        resultTable->setItem(i, 8, new QTableWidgetItem(QString::number(totalIssues)));

        // 根据情况设置行的颜色
        QColor rowColor;
        if (totalIssues > 0)
        {
            // 有问题的房间，标红
            rowColor = QColor(255, 200, 200); // 浅红色
        }
        else if (stats.excellentCount > 0 && stats.excellentCount >= stats.goodCount)
        {
            // 优秀居多的房间，标绿
            rowColor = QColor(200, 255, 200); // 浅绿色
        }
        else
        {
            // 一般的房间，标黄
            rowColor = QColor(255, 255, 200); // 浅黄色
        }

        // 应用颜色到行
        for (int col = 0; col < resultTable->columnCount(); ++col)
        {
            QTableWidgetItem *item = resultTable->item(i, col);
            if (item)
            {
                item->setBackground(rowColor);
                item->setTextAlignment(Qt::AlignCenter); // 文本居中
            }
        }
    }
}

void MonthlyQuery::sortData()
{
    if (currentSortType == SortByExcellent)
    {
        // 按照"优"的次数从大到小排序，但如果有问题记录则排在后面
        std::sort(currentStats.begin(), currentStats.end(), [](const Database::MonthlyStats &a, const Database::MonthlyStats &b)
                  {
            // 计算问题总数
            int aTotalIssues = a.fireIssueCount + a.smokingIssueCount + a.sanitaryIssueCount + a.safetyIssueCount;
            int bTotalIssues = b.fireIssueCount + b.smokingIssueCount + b.sanitaryIssueCount + b.safetyIssueCount;
            
            // 如果a有问题记录，b没有，则b排在前面
            if (aTotalIssues > 0 && bTotalIssues == 0) {
                return false;
            }
            // 如果b有问题记录，a没有，则a排在前面
            if (bTotalIssues > 0 && aTotalIssues == 0) {
                return true;
            }
            // 如果都有或都没有问题记录，则按优秀次数从大到小排序
            if (a.excellentCount != b.excellentCount) {
                return a.excellentCount > b.excellentCount;
            }
            // 如果优秀次数相同，则按单元和房间号排序
            if (a.unit != b.unit) {
                return a.unit < b.unit;
            }
            return a.room < b.room; });
    }
    else
    {
        // 按照问题总数从大到小排序
        std::sort(currentStats.begin(), currentStats.end(), [](const Database::MonthlyStats &a, const Database::MonthlyStats &b)
                  {
            // 计算问题总数
            int aTotalIssues = a.fireIssueCount + a.smokingIssueCount + a.sanitaryIssueCount + a.safetyIssueCount;
            int bTotalIssues = b.fireIssueCount + b.smokingIssueCount + b.sanitaryIssueCount + b.safetyIssueCount;
            
            // 首先按问题总数从大到小排序
            if (aTotalIssues != bTotalIssues) {
                return aTotalIssues > bTotalIssues;
            }
            // 如果问题总数相同，则按单元和房间号排序
            if (a.unit != b.unit) {
                return a.unit < b.unit;
            }
            return a.room < b.room; });
    }
}

void MonthlyQuery::onQueryClicked()
{
    loadData();
}

void MonthlyQuery::onSortExcellentClicked()
{
    currentSortType = SortByExcellent;
    if (!currentStats.isEmpty())
    {
        sortData();
        loadData(); // 重新加载以更新表格
    }
}

void MonthlyQuery::onSortPoorClicked()
{
    currentSortType = SortByPoor;
    if (!currentStats.isEmpty())
    {
        sortData();
        loadData(); // 重新加载以更新表格
    }
}

void MonthlyQuery::onExportExcelClicked()
{
    if (currentStats.isEmpty())
    {
        QMessageBox::warning(this, "导出失败", "没有数据可导出");
        return;
    }

    // 获取日期范围
    QString startDateStr = startDateEdit->date().toString("yyyyMMdd");
    QString endDateStr = endDateEdit->date().toString("yyyyMMdd");

    // 构建包含日期范围的文件名
    QString defaultFileName = QString("宿舍评分统计_%1至%2.xlsx").arg(startDateStr).arg(endDateStr);
    QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/" + defaultFileName;

    // 获取保存路径
    QString filePath = QFileDialog::getSaveFileName(this, "导出Excel",
                                                    defaultPath,
                                                    "Excel文件 (*.xlsx)");

    if (filePath.isEmpty())
    {
        return;
    }

    // 显示进度状态
    QApplication::setOverrideCursor(Qt::WaitCursor);
    // 不依赖MainWindow类，直接使用父窗口作为QMainWindow
    QMainWindow *mainWin = qobject_cast<QMainWindow *>(parent());
    if (mainWin)
    {
        mainWin->statusBar()->showMessage("导出中...");
    }

    // 导出Excel
    bool success = exportToExcel(filePath);

    // 恢复光标和状态栏
    QApplication::restoreOverrideCursor();
    if (mainWin)
    {
        mainWin->statusBar()->showMessage("准备就绪", 3000);
    }

    if (success)
    {
        QMessageBox::information(this, "导出成功", "数据已成功导出到: " + filePath);
    }
    else
    {
        QMessageBox::critical(this, "导出失败", "导出Excel文件失败");
    }
}

bool MonthlyQuery::exportToExcel(const QString &filePath)
{
#ifdef Q_OS_WIN
    // Windows平台使用ActiveX导出Excel
    try
    {
        // 创建Excel应用程序对象
        QAxObject excel("Excel.Application");
        excel.setProperty("Visible", false);

        // 添加工作簿
        QAxObject *workbooks = excel.querySubObject("Workbooks");
        workbooks->dynamicCall("Add");
        QAxObject *workbook = excel.querySubObject("ActiveWorkbook");

        // 获取活动工作表
        QAxObject *worksheet = workbook->querySubObject("ActiveSheet");

        // 添加日期范围信息的标题（在第1行）
        QString dateRangeTitle = QString("宿舍评分统计 (%1 至 %2)")
                                     .arg(startDateEdit->date().toString("yyyy-MM-dd"))
                                     .arg(endDateEdit->date().toString("yyyy-MM-dd"));
        QAxObject *titleCell = worksheet->querySubObject("Cells(int,int)", 1, 1);
        titleCell->setProperty("Value", dateRangeTitle);
        titleCell->setProperty("Font.Bold", true);
        titleCell->setProperty("Font.Size", 14);

        // 将标题单元格合并到整个标题行
        QAxObject *titleRange = worksheet->querySubObject("Range(QVariant,QVariant)", "A1:I1");
        titleRange->dynamicCall("Merge()");
        titleRange->setProperty("HorizontalAlignment", 3); // xlCenter

        // 设置主标题行现在移到第2行
        QStringList mainTitles = {"单元", "房间号", "优的次数", "良的次数", "差"};
        for (int i = 0; i < mainTitles.size(); ++i)
        {
            QAxObject *cell = worksheet->querySubObject("Cells(int,int)", 2, i + 1);
            cell->setProperty("Value", mainTitles[i]);
            cell->setProperty("Font.Bold", true);
            cell->setProperty("Interior.Color", QColor(224, 224, 224)); // 灰色背景
            cell->setProperty("HorizontalAlignment", 3);                // xlCenter

            // 设置列宽
            QAxObject *column = worksheet->querySubObject("Columns(int)", i + 1);
            column->setProperty("ColumnWidth", 15);
        }

        // 合并"差"标题单元格（从第5列开始，跨越5列）
        QAxObject *diffTitleRange = worksheet->querySubObject("Range(QVariant,QVariant)", "E2:I2");
        diffTitleRange->dynamicCall("Merge()");

        // 设置子标题行 - 第三行
        QStringList subTitles = {"消防问题", "抽烟问题", "卫生问题", "安全问题", "差累计"};
        for (int i = 0; i < subTitles.size(); ++i)
        {
            QAxObject *cell = worksheet->querySubObject("Cells(int,int)", 3, i + 5); // 从第5列开始
            cell->setProperty("Value", subTitles[i]);
            cell->setProperty("Font.Bold", true);
            cell->setProperty("Interior.Color", QColor(232, 232, 232)); // 浅灰色背景
            cell->setProperty("HorizontalAlignment", 3);                // xlCenter
        }

        // 合并前4列的标题单元格（横跨2行）
        for (int i = 0; i < 4; ++i)
        {
            QAxObject *range = worksheet->querySubObject("Range(QVariant,QVariant)",
                                                         QString("%1%2:%1%3").arg(QChar('A' + i)).arg(2).arg(3));
            range->dynamicCall("Merge()");
            range->setProperty("VerticalAlignment", 2); // xlCenter
        }

        // 设置所有标题单元格的边框
        QAxObject *allHeaderRange = worksheet->querySubObject("Range(QVariant,QVariant)", "A2:I3");
        QAxObject *borders = allHeaderRange->querySubObject("Borders");
        borders->setProperty("LineStyle", 1); // xlContinuous
        borders->setProperty("Weight", 2);    // xlThin

        // 填充数据（从第4行开始，因为标题现在占据了3行）
        for (int row = 0; row < currentStats.size(); ++row)
        {
            const Database::MonthlyStats &stats = currentStats[row];

            worksheet->querySubObject("Cells(int,int)", row + 4, 1)->setProperty("Value", stats.unit);
            worksheet->querySubObject("Cells(int,int)", row + 4, 2)->setProperty("Value", stats.room);
            worksheet->querySubObject("Cells(int,int)", row + 4, 3)->setProperty("Value", stats.excellentCount);
            worksheet->querySubObject("Cells(int,int)", row + 4, 4)->setProperty("Value", stats.goodCount);
            worksheet->querySubObject("Cells(int,int)", row + 4, 5)->setProperty("Value", stats.fireIssueCount);
            worksheet->querySubObject("Cells(int,int)", row + 4, 6)->setProperty("Value", stats.smokingIssueCount);
            worksheet->querySubObject("Cells(int,int)", row + 4, 7)->setProperty("Value", stats.sanitaryIssueCount);
            worksheet->querySubObject("Cells(int,int)", row + 4, 8)->setProperty("Value", stats.safetyIssueCount);
            worksheet->querySubObject("Cells(int,int)", row + 4, 9)->setProperty("Value", stats.poorCount);

            // 设置行的颜色
            QAxObject *range = worksheet->querySubObject("Range(QVariant,QVariant)",
                                                         QString("A%1:I%1").arg(row + 4));

            if (stats.poorCount > 0)
            {
                // 有问题的房间，标红
                range->setProperty("Interior.Color", QColor(255, 200, 200));
            }
            else if (stats.excellentCount > 0 && stats.excellentCount >= stats.goodCount)
            {
                // 优秀居多的房间，标绿
                range->setProperty("Interior.Color", QColor(200, 255, 200));
            }
            else
            {
                // 一般的房间，标黄
                range->setProperty("Interior.Color", QColor(255, 255, 200));
            }
        }

        // 设置所有数据单元格的边框
        if (currentStats.size() > 0)
        {
            QAxObject *allDataRange = worksheet->querySubObject("Range(QVariant,QVariant)",
                                                                QString("A4:I%1").arg(currentStats.size() + 3));
            QAxObject *dataBorders = allDataRange->querySubObject("Borders");
            dataBorders->setProperty("LineStyle", 1); // xlContinuous
            dataBorders->setProperty("Weight", 1);    // xlThin
        }

        // 自动调整列宽以适应内容
        QAxObject *usedRange = worksheet->querySubObject("UsedRange");
        usedRange->querySubObject("Columns")->dynamicCall("AutoFit");

        // 保存并关闭Excel
        workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(filePath));
        workbook->dynamicCall("Close()");
        excel.dynamicCall("Quit()");

        return true;
    }
    catch (...)
    {
        // 异常处理
        return false;
    }
#else
    // 非Windows平台导出CSV
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return false;

    QTextStream out(&file);
    // 设置UTF-8编码，解决中文乱码问题
    out.setCodec("UTF-8");

    // 添加日期范围信息的标题
    QString dateRangeTitle = QString("宿舍评分统计 (%1 至 %2)")
                                 .arg(startDateEdit->date().toString("yyyy-MM-dd"))
                                 .arg(endDateEdit->date().toString("yyyy-MM-dd"));
    out << dateRangeTitle << "\n\n";

    // 写入主标题行，使用Tab分隔，避免CSV解析问题
    out << "单元\t房间号\t优的次数\t良的次数\t差 - 消防问题\t差 - 抽烟问题\t差 - 卫生问题\t差 - 安全问题\t差累计\n";

    // 写入数据
    for (const Database::MonthlyStats &stats : currentStats)
    {
        // 使用Tab分隔字段，确保Excel可以正确解析
        out << stats.unit << "\t"
            << stats.room << "\t"
            << stats.excellentCount << "\t"
            << stats.goodCount << "\t"
            << stats.fireIssueCount << "\t"
            << stats.smokingIssueCount << "\t"
            << stats.sanitaryIssueCount << "\t"
            << stats.safetyIssueCount << "\t"
            << stats.poorCount << "\n";
    }

    file.close();

    // 修改文件扩展名为.tsv以表明是制表符分隔的文件
    if (filePath.endsWith(".xlsx", Qt::CaseInsensitive))
    {
        QString tsvPath = filePath.left(filePath.length() - 5) + ".tsv";
        QFile::rename(filePath, tsvPath);
        QMessageBox::information(nullptr, "文件格式改变",
                                 "由于当前平台限制，导出的文件已保存为TSV格式(Tab分隔值)：\n" + tsvPath);
    }

    return true;
#endif
}